#include <iostream>
#include "tocUtil.h"

#define SPACE 0.04
#define BITE_PROXIMITY 0.004
#define INITIAL_GHOUL_SPEED 0.00005

using namespace std;

static GLuint ghoulID = 0;

TOCGhoul::TOCGhoul(void) : TOCBody ()
{
	this->uuid = ghoulID++;
	this->setXY(0.0, 0.0); // Change Me
	initGhoul();
}

TOCGhoul::TOCGhoul(TOCHuman *victim)
{
	this->uuid = ghoulID++;
	this->setXY(victim->getX(), victim->getY());
	this->setLook(victim->getLook());

	initGhoul();
}

TOCGhoul::~TOCGhoul(void) {}

void TOCGhoul::initGhoul(void)
{
	this->rgb[0] = 1.0f;
	this->rgb[1] = 0.0f;
	this->rgb[2] = 0.0f;

	this->setSpeed(INITIAL_GHOUL_SPEED);
}

void TOCGhoul::_drawMe(void) 
{
	GLfloat e = 0.0;
	const GLfloat halfLength  = 0.007;
	const GLfloat halfBreadth = 0.003;

	glColor3fv(this->rgb);

	drawTriangle(this->getLook(), 
		     this->getX(), this->getY(), 
		     halfLength, halfBreadth, e);
}

GLfloat TOCGhoul::getDistance(TOCGhoul *him)
{
	return _getDistance(this->getX(), this->getY(), him->getX(), him->getY());
}

GLfloat TOCGhoul::getDistance(TOCHuman *him) 
{
	return _getDistance(this->getX(), this->getY(), him->getX(), him->getY());
}

void TOCGhoul::_moveToward(GLfloat x, GLfloat y)
{
	const GLfloat dX = this->getX() - x;
	const GLfloat dY = this->getY() - y;
	const GLfloat effectiveSpeed = this->getSpeed();


	if(dX > SPACE) {
		this->x-= effectiveSpeed;
		this->setLook(WEST);
	}
	else if(dX < -SPACE) {
		this->x += effectiveSpeed;
		this->setLook(EAST);
	}
	if(dY > SPACE) {
		this->y -= effectiveSpeed;
		this->setLook(SOUTH);
	}
	else if(dY < -SPACE) {
		this->y += effectiveSpeed;		
		this->setLook(NORTH);
	}
}

bool TOCGhoul::moveToward(GLfloat x, GLfloat y)
{

	_moveToward(x, y);

	return false; // There is no meaning to this bool value
}


bool TOCGhoul::moveToward(TOCHuman *him) 
{
	_moveToward(him->getX(), him->getY());

	if(_getDistance(this->getX(), this->getY(),
			him->getX(), him->getY()) <= BITE_PROXIMITY)
		return true;

	return false;
}

void TOCGhoul::addNewGhoulNeighbor(TOCGhoul &newNeighbor)
{
	this->ghoulNeighbors.push_back(newNeighbor);
}

TOCHuman *TOCGhoul::doGhoulStuff(
	vector<TOCGhoul> neighbors,
	TOCHuman *potentialVictim)
{
	if (potentialVictim != NULL) {
		this->setSpeed(this->getSpeed() + 0.0000003);
		if(this->moveToward(potentialVictim) == true) {
			this->setSpeed(INITIAL_GHOUL_SPEED); 
			return potentialVictim;
		}
	}
	else {
		this->setSpeed(INITIAL_GHOUL_SPEED);
		// if(this->ghoulNeighbors.size() > 0) {
		// 	vector<float> c = getCentroid(this->ghoulNeighbors);
		// 	this->moveToward(c[0], c[1]);
		// }
	}

	return NULL;
}

void TOCGhoul::_computeMove(void)
{
	switch (this->getLook()) {
	case NORTH:
		this->setXY(this->getX(), this->getY() + this->getSpeed());
		break;

	case EAST:
		this->setXY(this->getX() + this->getSpeed(), this->getY());
		break;

	case SOUTH:
		this->setXY(this->getX(), this->getY() - this->getSpeed());
		break;

	case WEST:
		this->setXY(this->getX() - this->getSpeed(), this->getY());
		break;
	}
}
